package com.yeziji.utils;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;

/**
 * 锁工具类
 *
 * @author hwy
 * @since 2023/09/09 17:22
 **/
public class LockUtils {
    private Lock lock;

    public static LockUtils newInstance(boolean isFair) {
        LockUtils lockUtils = new LockUtils();
        lockUtils.lock = new ReentrantLock(isFair);
        return lockUtils;
    }

    public void execute(Runnable runnable) {
        try {
            if (lock.tryLock()) {
                runnable.run();
            }
        } finally {
            lock.unlock();
        }
    }

    public <T, U> U execute(T data, Function<T, U> function) {
        try {
            if (lock.tryLock()) {
                return function.apply(data);
            }
        } finally {
            lock.unlock();
        }
        return null;
    }
}
